package com.sinosoft.cpyy.config.shardingjdbc;

import io.shardingjdbc.core.api.ShardingDataSourceFactory;
import io.shardingjdbc.core.api.config.ShardingRuleConfiguration;
import io.shardingjdbc.core.api.config.TableRuleConfiguration;
import io.shardingjdbc.core.api.config.strategy.InlineShardingStrategyConfiguration;
import org.springframework.beans.factory.annotation.Qualifier;

import javax.sql.DataSource;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

//@Configuration
public class ShardingConfiguration {

//    @Bean(name = "shardingJdbcMasterDataSource")
    public DataSource configSharding(@Qualifier("masterDataSource") DataSource masterDataSource) throws SQLException {
        Map<String, DataSource> dataSourceMap = new HashMap<>(1);
        dataSourceMap.put("masterDataSource", masterDataSource);

        // 配置分片规则
        ShardingRuleConfiguration shardingRuleConfig = new ShardingRuleConfiguration();
        shardingRuleConfig.getTableRuleConfigs().add(getTableRuleConfiguration());
        return ShardingDataSourceFactory.createDataSource(dataSourceMap,
                shardingRuleConfig,
                new HashMap<>(1),
                new Properties());
    }

    
    private TableRuleConfiguration getTableRuleConfiguration() {
        TableRuleConfiguration orderTableRuleConfig = new TableRuleConfiguration();
        orderTableRuleConfig.setLogicTable("HRSC_ORDER");
        //orderTableRuleConfig.setActualDataNodes("hrsc.HRSC_ORDER_${0..1}");
        orderTableRuleConfig.setTableShardingStrategyConfig(new InlineShardingStrategyConfiguration("CUST_ID", "HRSC_ORDER_${CUST_ID % 2}"));
        return orderTableRuleConfig;
    }
}
